"""Smart import API endpoints."""

from __future__ import annotations

from uuid import uuid4

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session

from app.api.deps import get_current_user, get_db
from app.api.utils import _ok
from app.models.user import User
from app.repositories.lead_repository import LeadRepository
from app.repositories.lead_intention_repository import LeadIntentionRepository
from app.schemas.lead_intention import LeadIntentionCreate
from app.services.smart_import_service import SmartImportService, ParsedLeadWithIntentions

router = APIRouter(tags=["smart-import"])


class SmartParseRequest(BaseModel):
    """智能解析请求."""

    texts: list[str] = Field(..., description="客户信息文本列表", min_length=1, max_length=100)


class SmartImportRequest(BaseModel):
    """智能导入请求."""

    items: list[ParsedLeadWithIntentions] = Field(..., description="解析后的客户数据", min_length=1)


@router.post("/parse", status_code=status.HTTP_200_OK)
async def smart_parse(
    request: SmartParseRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> JSONResponse:
    """
    智能解析客户信息（支持多意向）.

    流程：
    1. 用户粘贴文本（每行一个客户，或多段文本）
    2. AI 解析 → 返回结构化数据（主意向 + 额外意向）
    3. 前端展示审核界面
    4. 用户确认后调用 /import 接口

    支持：
    - 单意向客户：只有主意向
    - 多意向客户：主意向 + N个额外意向

    字数限制：
    - 单条文本：1000字符
    - 批量上限：100条（自动分批，每批5条）
    """
    # 初始化服务 (使用统一AI服务,自动选择GLM/Qwen/Hunyuan)
    smart_service = SmartImportService()

    try:
        # 批量解析
        result = await smart_service.parse_batch(request.texts)

        return _ok(
            {
                "items": [item.model_dump() for item in result.items],
                "total": result.total,
                "success": result.success,
                "failed": result.failed,
            },
            f"解析完成：成功{result.success}条，失败{result.failed}条",
        )

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"AI解析失败: {str(e)}",
        )


@router.post("/import", status_code=status.HTTP_201_CREATED)
async def smart_import(
    request: SmartImportRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> JSONResponse:
    """
    智能导入客户数据（含多意向）.

    流程：
    1. 接收前端审核通过的数据
    2. 创建客户记录（Lead）
    3. 创建额外意向记录（LeadIntention）
    4. 返回导入结果

    数据结构：
    - Lead表：主意向（必填）
    - LeadIntention表：额外意向（可选，可为空）
    """
    lead_repo = LeadRepository(db)
    intention_repo = LeadIntentionRepository(db)

    batch_id = uuid4()
    created_leads = []
    created_intentions = []
    errors = []

    try:
        for item in request.items:
            try:
                # 1. 创建客户（主意向）
                lead_data = item.lead.model_dump()
                lead_data["owner_id"] = current_user.id
                lead_data["import_batch_id"] = batch_id

                # 检查手机号重复
                existing = lead_repo.get_by_phone(lead_data["phone"])
                if existing:
                    errors.append(f"手机号 {lead_data['phone']} 已存在")
                    continue

                lead = lead_repo.create(item.lead.model_copy(update={
                    "owner_id": current_user.id,
                    "import_batch_id": batch_id
                }))
                created_leads.append(lead)

                # 2. 创建额外意向（如果有）
                if item.additional_intentions:
                    intentions_to_create = [
                        LeadIntentionCreate(
                            lead_id=lead.id,
                            **intention.model_dump()
                        )
                        for intention in item.additional_intentions
                    ]

                    intentions = intention_repo.create_batch(intentions_to_create)
                    created_intentions.extend(intentions)

            except Exception as e:
                errors.append(f"导入失败: {str(e)}")
                continue

        # 提交事务
        db.commit()

        return _ok(
            {
                "batch_id": str(batch_id),
                "created_leads": len(created_leads),
                "created_intentions": len(created_intentions),
                "errors": errors,
            },
            f"导入完成：成功{len(created_leads)}个客户，{len(created_intentions)}个额外意向",
            status.HTTP_201_CREATED,
        )

    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"导入失败: {str(e)}",
        )
